package com.david.core.normalreq

import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors


class UrlHttpRequest {
    var exccutors = Executors.newFixedThreadPool(3)
    fun getRequest(tempUrl:String, params:String, response: UrlHttpResponse){
        exccutors.submit(Runnable {
            try {
                val url = URL(tempUrl)
                //得到connection对象。
                val connection = url.openConnection() as HttpURLConnection
                //设置请求方式
                connection.requestMethod = "GET"
                //连接
                connection.connect()
                //得到响应码
                val responseCode = connection.responseCode
                if(responseCode == HttpURLConnection.HTTP_OK){
                    //得到响应流
                    val inputStream = connection.inputStream
                    //将响应流转换成字符串
                    val inputStreamReader = InputStreamReader(inputStream)
                    val bufferedReader = BufferedReader(inputStreamReader)

                    var result = ""//将流转换为字符串。
                    var line = bufferedReader.readLine()
                    while ((line) != null) {
                        result+=line
                        line = bufferedReader.readLine()
                    }
                    inputStream.close()
                    inputStreamReader.close()
                    bufferedReader.close()

                    response.onSuccess(result)
                } else {
                    response.onFail(responseCode.toString())
                }

            } catch (e:Exception) {
                e.printStackTrace()
                response.onFail(e.message.toString())
            }
        })
    }
}